package com.demo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.domain.PageResult;
import com.basic.util.ConverterUtil;
import com.basic.util.QueryHelpPlus;
import com.demo.mapper.OrderMapper;
import com.demo.pojo.Order;
import com.demo.service.IOrderService;
import com.demo.service.IUserService;
import com.demo.service.criteria.OrderLinkProductQueryCriteria;
import com.demo.service.criteria.OrderQueryCriteria;
import com.demo.service.dto.OrderDto;
import com.demo.service.dto.OrderLinkProductDto;
import com.demo.service.vo.MyConverterUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-12
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private final OrderMapper orderMapper;

    private final IUserService userService;

    public OrderServiceImpl(OrderMapper orderMapper, IUserService userService) {
        this.orderMapper = orderMapper;
        this.userService = userService;
    }

    @Override
    public OrderDto saveOrUpdate(OrderDto orderDto) {
        final Order order = ConverterUtil.convert(orderDto, Order.class);
        if (ObjectUtil.isNull(order.getId())) {
            baseMapper.insert(order);
        } else {
            baseMapper.updateById(order);
        }
        return convertDto(order, null);
    }

    @Override
    public List<OrderDto> queryAll(OrderQueryCriteria criteria) {
        return convertDto(baseMapper.selectList(query(criteria)), criteria);
    }

    @Override
    public PageResult<OrderDto> queryAll(OrderQueryCriteria criteria, Pageable pageable) {
        int page;
        int limit;
        if (criteria.getPage() != null && criteria.getLimit() != null) {
            page = criteria.getPage();
            limit = criteria.getLimit();
        } else {
            page = pageable.getPageNumber();
            limit = pageable.getPageSize();
        }
        final IPage<Order> pageList = baseMapper.selectPage(new Page<>(page, limit), query(criteria));

        return new PageResult<>(pageList.getTotal(), convertDto(pageList.getRecords(), criteria));
    }

    @Override
    public OrderDto queryById(Long id) {
        final List<OrderDto> records = queryAll(OrderQueryCriteria.builder().id(id).build());
        if (!records.isEmpty()) {
            return records.get(0);
        }
        return null;
    }

    @Override
    public OrderDto queryOne(OrderQueryCriteria criteria) {
        final List<OrderDto> records = queryAll(criteria);
        if (!records.isEmpty()) {
            return records.get(0);
        }
        return null;
    }

    @Override
    public Long count(OrderQueryCriteria criteria) {
        return baseMapper.selectCount(query(criteria));
    }

    @Override
    public Order getOne(OrderQueryCriteria criteria) {
        final List<Order> records = getAll(criteria);
        if (!records.isEmpty()) {
            return records.get(0);
        }
        return null;
    }

    @Override
    public List<Order> getAll(OrderQueryCriteria criteria) {
        return baseMapper.selectList(query(criteria));
    }

    @Override
    public int deleteId(Long id) {
        final OrderDto orderDto = queryById(id);
        delete(orderDto);
        return 1;
    }

    @Override
    @Transactional
    public int deleteByMore(OrderQueryCriteria criteria) {
        final List<OrderDto> orderDtos = queryAll(criteria);
        for (OrderDto each: orderDtos) {
            delete(each);
        }
        return orderDtos.size();
    }

    private void delete(OrderDto orderDto) {
        orderDto.setIsShow(0);
        saveOrUpdate(orderDto);
    }

    @Override
    public List<Order> testXml() {
        return orderMapper.selectAllData();
    }

    @Override
    public List<OrderLinkProductDto> queryAllLinkProduct(OrderLinkProductQueryCriteria criteria) {
        return convertProductDto(orderMapper.selectListLinkProduct(linkProductQuery(criteria)), criteria);
    }

    /**
     * 后续所有的sql逻辑都在这里处理
     */
    private QueryWrapper<Order> query(OrderQueryCriteria criteria) {
        QueryWrapper<Order> wrapper = QueryHelpPlus.getPredicate(Order.class, criteria);
        if (ObjectUtil.isNull(criteria)) {
            return wrapper;
        }

        if (ObjectUtil.isNull(criteria.getIsShow())) {
            wrapper.eq("is_show", 1);
        }

        return wrapper;
    }

    /**
     * 后续所有的sql逻辑都在这里处理
     */
    private QueryWrapper<Order> linkProductQuery(OrderLinkProductQueryCriteria criteria) {
        final QueryWrapper<Order> wrapper = QueryHelpPlus.getPredicate(Order.class, criteria);
        wrapper.select("o.*", "p.*");
        if (ObjectUtil.isNull(criteria)) {
            return wrapper;
        }

        if (ObjectUtil.isNull(criteria.getIsShow())) {
            wrapper.eq("o.is_show", 1);
        }

        return wrapper;
    }

    private OrderDto convertDto(Order record, OrderQueryCriteria criteria) {
        return MyConverterUtils.INSTANCE.toOrderDto(record);
    }

    private List<OrderDto> convertDto(List<Order> records, OrderQueryCriteria criteria) {

        final List<OrderDto> result = new ArrayList<>();

        for (Order each : records) {
            result.add(convertDto(each, criteria));
        }

        return result;
    }


    private List<OrderLinkProductDto> convertProductDto(List<OrderLinkProductDto> orderLinkProductDtos, OrderLinkProductQueryCriteria criteria) {

        if (ObjectUtil.isNull(criteria) || orderLinkProductDtos.isEmpty()) {
            return orderLinkProductDtos;
        }

        for (OrderLinkProductDto each : orderLinkProductDtos) {
            if (ObjectUtil.defaultIfNull(criteria.getIsQueryUser(), Boolean.FALSE)) {
                each.setUserDto(userService.queryById(each.getUserId()));
            }
        }

        return orderLinkProductDtos;
    }
}
